import React, {Component} from 'react'
import { bindActionCreator } from './qdx-redux'
import PropTypes from 'prop-types';

export class Provider extends Component{
  static childContextTypes = {
    store: PropTypes.object
  }
  constructor(props, context){
    super(props, context)
    this.store = props.store
  }
  getChildContext(){
    return {
      store: this.store
    }
  }
  render(){
    return this.props.children
  }
}

export const connect = (mapStateToProps, mapDispatchToProps) => (Comp) => {
  return class WrapComponent extends Component{
    static contextTypes = {
      store: PropTypes.object
    }
    constructor(props, context){
      super(props, context)
      this.state = {
        props:{

        }
      }
    }
    componentDidMount() {
      const { store } = this.context
      //当进行dispatch的时候进行一次数据更新操作
      store.subscribe(() => this.update())
      this.update()
    }
    update(){
      const { store } = this.context
      //直接对数据进行处理因为mapStateToProps返回的是一个对象，因此可以直接作为一个参数进行处理
      const stateProps = mapStateToProps(store.getState())
      //dispatch返回的就仅仅为一个简单的对象，这个时候就需要手动的dispatch一次数据
      const dispatchProps = bindActionCreator(mapDispatchToProps, store.dispatch)
      this.setState({
        props:{
          ...this.state.props,
          ...stateProps,
          ...dispatchProps
        }
      })
    }
    render(){
      return <Comp {...this.state.props}></Comp>
    }
  }
}